import cv2
import numpy as np
import face_recognition
import os
# 加载图片
path = "C:/Users/shouw/Desktop/tmp/known_pictures"
person_encodings = []
person_names = []

imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
for imagePath in imagePaths:
    name = os.path.split(imagePath)[-1].split(".")[0]
    img = face_recognition.load_image_file(imagePath)

    person_encoding = face_recognition.face_encodings(img)[0]
    person_encodings.append(person_encoding)
    person_names.append(name)

face_locations = []
face_encodings = []
face_names = []
frame_num = 0

cap = cv2.VideoCapture(0)
cap.set(3, 352)
cap.set(4, 288)

while cap.isOpened():
    ret, frame = cap.read()
    rgb_img = frame[:, :, ::-1]     # BGR格式-》RGB格式
    # 对当前人脸定位，并对脸部区域进行编码
    face_recognitions = face_recognition.face_locations(rgb_img)
    face_locations = face_recognition.face_locations(rgb_img)
    face_encodings = face_recognition.face_encodings(rgb_img, face_locations)
    face_names = []

    for face_encoding in face_encodings:       # 与已知人脸比对
        matches = face_recognition.compare_faces(person_encodings, face_encoding, tolerance=0.5)
        name = "unknown"
        face_distances = face_recognition.face_distance(person_encodings, face_encoding)
        print(face_distances)
        best_match = np.argmin(face_distances)
        if matches[best_match]:
            name = person_names[best_match]
        face_names.append(name)


    # 遍历查找的人脸，标识结果
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        cv2.rectangle(frame, (left, top), (right, bottom), (255, 255, 255), 2)
        cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
        cv2.putText(frame, str(face_distances[best_match]), (left + 30, top), cv2.FONT_HERSHEY_COMPLEX, 0.5,
                    (255, 255, 255))

    cv2.imshow('Recognizing face', frame)
    if cv2.waitKey(1) & 0xFF == 27:  # 按ESC键退出
        break
cap.release()
cv2.destroyAllWindows()

